﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Threading;

namespace MuseumQuiz.Web
{
    [ServiceContract(Namespace = "")]
    [SilverlightFaultBehavior]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class MuseumQuizService
    {
        [OperationContract]
        public void DoWork()
        {
            return;
        }

        [OperationContract]
        public List<QuizVragen> Get3RandomQuestions()
        {
            List<QuizVragen> mijnQuizVragen = new List<QuizVragen>();
            MuseumDataClassesDataContext db = new MuseumDataClassesDataContext();
            
            while(mijnQuizVragen.Count != 3)
            {
                int r = GetRandomNumFromDB();
                var result = from v in db.QuizVragens where v.vraagID == r select v;
                List<QuizVragen> herpderp = result.ToList();
                if (herpderp.Count != 0)
                {
                    if (!mijnQuizVragen.Contains(result.First()))
                    {
                        mijnQuizVragen.Add(result.First());
                    }
                    Thread.Sleep(100);
                }
            }
            return mijnQuizVragen;
        }

        public int GetRandomNumFromDB()
        {
            MuseumDataClassesDataContext db = new MuseumDataClassesDataContext();
            int random;
            //max is de grootste vraagID
            int max = (from v in db.QuizVragens select v.vraagID).Max();
            do
            {
                Random r = new Random();
                random = r.Next(1, max+1);
            }while((from v in db.QuizVragens where v.vraagID == random select v) == null);
            //op dit moment is er een random int gevonden die ook
            //effectief bestaat als vraagID
            return random;
        }

        // Add more operations here and mark them with [OperationContract]
    }
}
